#!/bin/sh
#
# PROVIDE: medusa
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# medusa_enable (bool):	Set to NO by default.
#			Set it to YES to enable it.
# medusa_user:	The user account Medusa daemon runs as what
#			you want it to be. It uses 'medusa' user by
#			default. Do not sets it as empty or it will run
#			as root.
# medusa_group:	The group account Medusa daemon runs as what
#			you want it to be. It uses 'medusa' group by
#			default. Do not sets it as empty or it will run
#			as wheel.
# medusa_dir:	Directory where Medusa lives.
#			Default: /usr/local/medusa
# medusa_datadir:	Data directory for Medusa (DB, Logs, config)
#			Default is same as medusa_dir
# medusa_python_dir: The directory where python is installed.
#			Default: /usr/local/bin/python3.7

. /etc/rc.subr

name="medusa"
rcvar=${name}_enable

load_rc_config ${name}

: ${medusa_enable:="NO"}
: ${medusa_user:="medusa"}
: ${medusa_group:="medusa"}
: ${medusa_dir:="/usr/local/medusa"}
: ${medusa_datadir:="${medusa_dir}"}
: ${medusa_python_dir="/usr/local/bin/python3.7"}

pidfile="/var/run/PyMedusa/Medusa.pid"
pidfile_child="/var/run/PyMedusa/Medusa_child.pid"
command="/usr/sbin/daemon"
command_args="-cf -P ${pidfile} -p ${pidfile_child} ${medusa_python_dir} ${medusa_dir}/start.py -q --nolaunch --pidfile /var/run/Pymedusa/child.pid --datadir ${medusa_datadir}"

start_precmd="medusa_prestart"
stop_precmd="medusa_prestop"
stop_postcmd="medusa_poststop"

medusa_prestart() {
	if [ -f ${pidfile} ]; then
		rm -f ${pidfile}
		echo "Removing stale pidfile."
	elif [ ! -d ${pidfile%/*} ]; then
		install -d -o ${medusa_user} -g ${medusa_group} ${pidfile%/*}
	fi

	if [ ! -d ${medusa_datadir} ]; then
		install -d -o ${medusa_user} -g ${medusa_group} ${medusa_datadir}
	fi
}

medusa_prestop() {
	if [ -r ${pidfile} ]; then
		export _MEDUSAPID=$(check_pidfile ${pidfile} daemon)
	fi
}

medusa_poststop() {	
	_MEDUSA_CHILDREN=$(pgrep -g ${_MEDUSAPID})
	echo "Waiting for child processes to stop."
	kill -3 ${_MEDUSA_CHILDREN}
	wait_for_pids ${_MEDUSA_CHILDREN}
}

run_rc_command "$1"
